<?php

namespace app\api\controller;


use addons\epay\library\Service;
use app\admin\model\BillModel;
use app\admin\model\DiyPushModel;
use app\admin\model\HouseCollectModel;
use app\admin\model\HouseOwnerModel;
use app\admin\model\HouseVisitModel;
use app\admin\model\RoomBoardLogModel;
use app\admin\model\UserExt;
use app\admin\model\UserLevelModel;
use app\admin\model\UserLoginLogModel;
use app\admin\model\UserRechargeConfigModel;
use app\admin\model\UserRechargeModel;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\library\Wechat;
use app\common\model\ScoreLog;
use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin','wxlogin', 'mpLogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third','wxreg'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
		$user = $this->auth->getUser();
        $this->success('成功', $user);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function wxlogin()
    {

        if(request()->domain() == 'https://house.xiaogangjt.com'){
            $appid = 'wxf7e632e0d265559a';
            $appsecret = '29d8e0c8ec069ad6093dd0ff9e73ec38';
        }else {
            $appid = 'wx833c968d9747af27';
            $appsecret = '42e699c825d897c67749e759097d6eb4';
        }
        $code = input('code');
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code={$code}&grant_type=authorization_code";
        $client = new \GuzzleHttp\Client();
        $result = $client->get($url)->getBody()->getContents();
        $api_data = json_decode($result, true);
//        var_export($api_data);
        // $api_data = array ( 'session_key' => 'BldZ3kGiYb/S9GDv++WYzA==', 'openid' => 'ocvDX5fu7teq62TErrIFqrCe4gmM', );
        if(isset($api_data['openid'])){
            $openid = $api_data['openid'];
            $user = Db::table('fa_user')->where('openid', $openid)->find();
            if(!empty($user)){
                $id = $user['id'];
            }else{
                $insert = [
                    'openid' => $api_data['openid'],
                    'logintime'=>time(),
                    'joinip'=>request()->ip(),
                    'jointime'=>time(),
                    'utype' => 2,
                    'status'=>'normal',
                ];
                $id =  Db::table('fa_user')->insertGetId($insert);
            }
            $ret = $this->auth->direct($id);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        }else{
            $this->error($api_data);
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    public function user_info()
    {
        $data = ['userinfo' => $this->auth->getUserinfo()];
        $this->success('成功', $data);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if (empty($username) && !empty($nickname)) {
            $username = $nickname;
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
            $user->nickname = $username;
        }
        /*if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
              //  $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }*/
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        $this->success('成功');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }



    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    // 小程序登录
    public function mpLogin()
    {
        $this->request->filter(['trim']);
        $params = $this->request->param();

        if (empty($params['code'])) {
            $this->error('code不能为空');
        }
        if (empty($params['phone_code'])) {
            $this->error('phone_code不能为空');
        }

        try {
            $wechat = new Wechat($this->cun_id);
        } catch (\Throwable $e) {
            $this->error($e->getMessage());
        }

        $result = $wechat->code($params['code']);
        if (empty($result) || isset($result['errcode'])) {
            trace('调用jscode2session失败');
            $this->error('登录失败'. ($result['errmsg'] ?? ''));
        }
        $phone = $wechat->phoneNumber($params['phone_code']);
        if ($phone['errcode'] != 0) {
            $this->error('获取手机号失败'. ($result['errmsg'] ?? ''));
        }
        $mobile = $phone['phone_info']['phoneNumber'] ?? '';
        if (empty($mobile)) {
            $this->error('获取手机号失败');
        }
        $openid = $result['openid'];
        $user = \app\common\model\User::getByMobile($mobile);
        if (!$user) {
            $password = Random::alnum();
            $username = '用户' . Random::numeric();
            $ret = $this->auth->register($username, $password, '', $mobile, [
                'openid' => $openid,
                'cun_id' => $this->cun_id
            ]);
        } else {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            $user->mobile = $mobile;
            $user->save();
            $ret = $this->auth->direct($user->id);
        }

        if ($ret) {
            $user_ext = UserExt::where([
                'user_id' => $this->auth->id,
                'cun_id' => $this->cun_id,
            ])->find();
            if(!$user_ext){
                UserExt::create([
                    'user_id' => $this->auth->id,
                    'cun_id' => $this->cun_id,
                    'openid' => $openid,
                ]);
            }
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->login_score(1);
            UserLoginLogModel::create([
                'user_id' => $this->auth->id,
                'ip' => $this->request->ip(),
            ]);
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }

    }

    public function login_score($return = 0)
    {
        $cache_key = sprintf('login_give_score:%s:%s', $this->auth->id, date('Ymd'));
        if (!cache($cache_key)) {
            $score_res = \app\common\model\User::score(1, $this->auth->id, '登录赠送', 3);
            if ($score_res) {
                cache($cache_key,1, 86400);
            }
        }
        if ($return) return true;
        $this->success();
    }

    public function checkCard($idCard)
    {
        $pattern = '/^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[\dXx]$/';
        if (!preg_match($pattern, $idCard)) {
            return '身份证号格式错误'; // 格式错误
        }
        return true;
    }

    //房主认证
    public function house_owner_auth()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'card_front|身份证正面照' => 'require',
            'card_back|身份证反面照' => 'require',
            'real_name|姓名' => 'require',
            'card_no|身份证号' => 'require|checkCard',
            'password|密码' => 'require|alphaNum|confirm',
            'password_confirm|确认密码' => 'require',
            //'bank_name|银行名称' => 'require',
            //'bank_card_no|银行卡号' => 'require',
            //'bank_city|开户城市' => 'require',
            //'bank_branch|开户支行' => 'require',
        ], [
            'password.confirm' => '密码和确认密码不一致'
        ], false, function ($v, $data) {
            $v->extend([
                'checkCard' => [$this, 'checkCard'],
            ]);
        });
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $pass_len = strlen($params['password']);
        if ($pass_len < 8 || $pass_len > 16 ) {
            $this->error('密码请输入8~16位字母或数字');
        }
        $model = new HouseOwnerModel();
        $user_id = $this->auth->id;
        $owner = $model->get(['user_id' => $user_id]);
        if($owner && $owner->status == 1) {
            $this->error('已认证通过，请勿重复提交');
        }
        $allowFields = [
            'user_id', 'card_front', 'card_back', 'real_name', 'card_no','status','password','salt'
        ];
        $params['user_id'] = $user_id;
        $params['status'] = 0;
        $params['salt'] = Random::alnum();
        $params['password'] = $this->auth->getEncryptPassword($params['password'], $params['salt']);
        $params['password_time'] = date('Y-m-d H:i:s');
        if ($owner) {
            $result = $owner->allowField($allowFields)->save($params);
        } else {
            $result = $model->create($params, $allowFields);
        }


        if ($result) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    public function isCheckPassword()
    {
        $user_id = $this->auth->id;
        $row = HouseOwnerModel::get(['user_id' => $user_id]);
        $result = 0;
        if (!empty($row)) {
            if (!$row->password_time || strtotime('+7 days', strtotime($row->password_time)) < time()) {
                $result = 1;
            }
        }
        $this->success('ok', $result);
    }

    // 验证房主密码
    public function verify_password()
    {
        $password =  $this->request->param('password');
        if (empty($password)) {
            $this->error('密码不能为空');
        }
        $user_id = $this->auth->id;
        $row = HouseOwnerModel::get(['user_id' => $user_id]);
        if (empty($row)) {
            $this->error('未认证');
        }
        if ($row->password != $this->auth->getEncryptPassword($password, $row->salt)) {
            $this->error('密码不正确');
        }
        $row->password_time = date('Y-m-d H:i:s');
        $row->save();
        $this->success('密码正确');
    }

    // 重置房东密码
    public function reset_owner_pwd()
    {
        $params = $this->request->post();
        $checkRes = $this->validate($params, [
            'mobile|手机号' => 'require',
            'captcha|验证码' => 'require',
            'password|密码' => 'require|alphaNum|confirm',
            'password_confirm|确认密码' => 'require',
        ], [
            'password.confirm' => '密码和确认密码不一致'
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }
        $pass_len = strlen($params['password']);
        if ($pass_len < 8 || $pass_len > 16) {
            $this->error('密码请输入8~16位字母或数字');
        }
        if ($this->auth->mobile != $params['mobile']) {
            $this->error('手机号和注册手机号不一致');
        }
        $ret = Sms::check($params['mobile'], $params['captcha'], 'resetpwd');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        Sms::flush($params['mobile'], 'resetpwd');
        $user_id = $this->auth->id;
        $row = HouseOwnerModel::get(['user_id' => $user_id]);
        if (empty($row)) {
            $this->error('未认证');
        }
        $row->salt = Random::alnum();
        $row->password = $this->auth->getEncryptPassword($params['password'], $row->salt);
        $row->password_time = null;
        $row->save();
        $this->success('重置成功');
    }

    /**
     * 获取房主认证信息
     * @return void
     * @throws DbException
     */
    public function house_owner_auth_info()
    {
        $model = new HouseOwnerModel();
        $user_id = $this->auth->id;
        $data = $model->get(['user_id' => $user_id]);
        $this->success('成功', $data);
    }

    /**
     * 收藏列表
     * @return void
     * @throws DbException
     */
    public function collect_list()
    {
        $kw = $this->request->param('keyword');
        $where = [];
        $where['house.status'] = 1;
        $where['collect.user_id'] = $this->auth->id;
        if (!empty($kw)) {
            $where['house.name'] = ['like', '%' . $kw . '%'];
        }
        $field = 'house.id,house.name,house.floor,house.area,house_type,rent,tags,images,collect.house_id,collect.create_time';
        $limit = $this->request->param('page_size/d', 15);
        $sort = 'id';
        $order = 'desc';
        $list = (new HouseCollectModel())->alias('collect')
            ->join('house', 'collect.house_id = house.id', 'left')
            ->where($where)
            ->order($sort, $order)
            ->field($field)
            ->paginate($limit)->each(function ($item) {
                $item->append(['tags_text','house_type_text']);
            });

        $this->success('成功', $list);
    }

    /**
     * 浏览列表
     * @return void
     * @throws DbException
     */
    public function visit_list()
    {
        $kw = $this->request->param('keyword');
        $where = [];
        $where['house.status'] = 1;
        $where['visit.user_id'] = $this->auth->id;
        if (!empty($kw)) {
            $where['house.name'] = ['like', '%' . $kw . '%'];
        }
        $field = 'house.id,house.name,house.floor,house.area,house_type,rent,tags,images,visit.house_id,visit.create_time';
        $limit = $this->request->param('page_size/d', 15);
        $sort = 'visit_time';
        $order = 'desc';
        $list = (new HouseVisitModel())->alias('visit')
            ->join('house', 'visit.house_id = house.id', 'left')
            ->where($where)
            ->order($sort, $order)
            ->field($field)
            ->paginate($limit)->each(function ($item) {
                $item->append(['tags_text','house_type_text']);
            });

        $this->success('成功', $list);
    }

    public function level_list()
    {
        //$list = UserLevelModel::all();
        $list = UserRechargeConfigModel::field('id,score,price')->select();
        $this->success('成功', $list);
    }

    public function recharge()
    {
        $id = $this->request->param('id/d', 0);
        $level_info = UserRechargeConfigModel::get($id);
        if (empty($level_info)) $this->error('配置不存在');

        if ($id == 1) {
            $count = UserRechargeModel::where([
                'user_id' => $this->auth->id,
                'status' => 1,
                'level_id' => $id,
            ])->count();
            if ($count) {
                $this->error('首次充值已使用过了');
            }
        }
        Db::startTrans();
        try {
            $order_no = date('YmdHis') . Random::numeric(6);
            UserRechargeModel::create([
                'order_no' => $order_no,
                'user_id' => $this->auth->id,
                'money' => $level_info['price'],
                'level_id' => $id,
                'score' => $level_info['score'],
            ]);

            //回调链接
            $notifyurl = $this->request->root(true) . '/api/notify/pay_success';
            $amount = $level_info['price'];
            $title = '开通会员';
            $method = 'miniapp';
            $openid = $this->auth->openid;
            if (empty($openid)) throw new Exception('请先绑定小程序');
            $data = Service::submitOrder($amount, $order_no, 'wechat', $title, $notifyurl, '', $method, $openid);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('success', $data ?? []);
    }


    public function diy_push()
    {
        $params = $this->request->param();
        $checkRes = $this->validate($params, [
            'community|社区' => 'require',
            'min_rent|最小租金' => 'integer',
            'max_rent|最大租金' => 'integer',
            'min_floor|最小楼层' => 'integer',
            'max_floor|最大楼层' => 'integer',
            'house_type|户型' => 'integer',
            'payment_type|付款方式' => 'integer',
        ]);
        if ($checkRes !== true) {
            $this->error($checkRes);
        }

        Db::startTrans();
        try {
            $params['user_id'] = $this->auth->id;
            if (empty($this->auth->openid)) {
                throw new Exception('未绑定小程序');
            }
            DiyPushModel::create($params, true);

            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

    public function sign()
    {
        $score = ScoreLog::where([
            'user_id' => $this->auth->id,
            'type' => 1,
            'createtime' => ['>=', strtotime(date('Y-m-d'))]
        ])->find();
        if (!empty($score)) {
            $this->error('今天已经签到过了，请勿重复签到');
        }

        $sign_score = (int)config('site.sign_score');
        $res = \app\common\model\User::score($sign_score, $this->auth->id, '签到积分', 1);
        if ($res) {
            $this->success('签到成功');
        } else {
            $this->error('签到失败');
        }

    }

    public function sign_stat()
    {
        $total_sign_score = ScoreLog::where([
            'user_id' => $this->auth->id,
            'type' => 1
        ])->sum('score');
        $data = [
            'score'=>$this->auth->score,
            'total_sign_score'=>$total_sign_score,
        ];
        $this->success('', $data);
    }

    public function sign_list()
    {
        $page_size = $this->request->param('page_size/d', 31);
        $month = $this->request->param('month');
        $where = [];
        $where['user_id'] = $this->auth->id;
        $order['id'] = 'desc';
        if (!empty($month)) {
            $where['type'] = 1;
            $where[] = Db::raw("DATE_FORMAT(FROM_UNIXTIME(createtime), '%Y-%m') = '{$month}'");
            $order['id'] = 'asc';
        }
        $list = ScoreLog::where($where)->order($order)->paginate($page_size);

        $this->success('', $list);
    }

    public function wxreg(){
        $avatar = $this->request->post("avatar");
        $nickname = $this->request->post("nickname");
        $encryptedData = $this->request->post('encryptedData', '', 'trim');
        $iv = $this->request->post('iv');
        //$mobile_code = $this->request->post("mobile_code");
        $code = $this->request->post("code");
        $appid = 'wxf7e632e0d265559a';
        $appsecret = '29d8e0c8ec069ad6093dd0ff9e73ec38';
        $params = [
            'appid'      => $appid,
            'secret'     => $appsecret,
            'js_code'    => $code,
            'grant_type' => 'authorization_code'
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
        if ($result['ret']) {
            $json = (array)json_decode($result['msg'], true);
            ///var_dump($json);exit;
            $aesIV = base64_decode($iv);
            $aesCipher = base64_decode($encryptedData);
            $aesKey = base64_decode($json['session_key']);
            $re = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
            $data = json_decode($re, true);
            trace('登录start');
            trace($data);
            trace('登录end');
            if ($data) {
                //  $user = \app\common\model\User::getByMobile($data['phoneNumber']);
                $user = Db::name("user")->where(['mobile'=>$data['phoneNumber']])->find();
                if ($user) {
                    if ($user['status'] != 'normal') {
                        $this->error(__('Account is locked'));
                    }
                    //如果已经有账号则直接登录
                    $ret = $this->auth->direct($user['id']);
                } else {
                    $ret = $this->auth->register($data['phoneNumber'], Random::alnum(), '', $data['phoneNumber'], ["openid"=>$json['openid'],'avatar'=>$avatar?$avatar:'','nickname'=>$nickname?$nickname:'']);
                }
                if ($ret) {
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('Logged in successful'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            } else {
                $this->error("配置参数错误");
            }
        } else {
            $this->error("授权失败");
        }
    }
    public function qrcode()
    {
        $data = [
            //'gzh'=>request()->domain().'/gzh.jpg',
            'gzh'=> request()->domain().'/'.Db::table('fa_shequconfig')->where('id',2)->value('gzh_image'),
           //'kefu'=>request()->domain().'/kefu.png',
            'kefu'=> request()->domain().'/'.Db::table('fa_shequconfig')->where('id',3)->value('gzh_image'),
            'userinfo'=>$this->auth->getUserinfo(),
           ];
        $this->success('成功',$data);
    }


    public function login_log()
    {
        $page_size = $this->request->param('page_size', 10);
        $create_time = $this->request->param('create_time', '');
        $where = [];
        if (!empty($create_time)) {
            $range = explode(' - ', $create_time);
            $where['create_time'] = ['between', $range];
        }
        $list = UserLoginLogModel::where('user_id', $this->auth->id)
            ->where($where)
            ->field('id,ip,create_time')
            ->order('id', 'desc')
            ->paginate($page_size)->each(function ($item) {

            });

        $this->success('success', $list);
    }

    public function month_income()
    {
        $money = BillModel::where([
            'user_id' => $this->auth->id,
            'type' => ['in', [1, 3, 4, 5, 6]],
            'status' => 2,
            'month' => date('Y-m')
        ])->sum('money');


        $this->success('ok', compact('money'));
    }
    public function addSzclassify(){
        $pid = $this->request->post('pid',0);
        $name = $this->request->post('name');
        $remarks = $this->request->post('remarks','');
        if(!$name){
            $this->error("缺少必传参数");
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['pid'] = $pid;
        $add_data['name'] = $name;
        $add_data['remarks'] = $remarks;
        $add_data['createtime'] = time();
        Db::name("szclassify")->insertGetId($add_data);
        $this->success("分类添加成功");
    }
    public function getPidSzclassify(){
        $pid = $this->request->post('pid',0);
        $data = Db::name("szclassify")->where(['pid'=>$pid])->select();
        $this->success("分类列表",$data);
    }
    public function getPidSzclassifyInfo(){
        $id = $this->request->post('id');
        $data = Db::name("szclassify")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        $this->success("分类信息",$data);
    }
    public function deleteSzclassify(){
        $id = $this->request->post('id');
        Db::name("szclassify")->where(['id'=>$id])->delete();
        $this->success("分类删除");
    }
    public function saveSzclassify(){
        $id = $this->request->post('id');
        $pid = $this->request->post('pid',0);
        $name = $this->request->post('name');
        $remarks = $this->request->post('remarks','');
        if(!$name){
            $this->error("缺少必传参数");
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['pid'] = $pid;
        $add_data['name'] = $name;
        $add_data['remarks'] = $remarks;
        $add_data['updatetime'] = time();
        Db::name("szclassify")->where(['id'=>$id])->update($add_data);
        $this->success("分类更新成功");
    }
    public function addSzledger(){
        $name = $this->request->post('name');
        $remarks = $this->request->post('remarks','');
        if(!$name){
            $this->error("缺少必传参数");
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['name'] = $name;
        $add_data['remarks'] = $remarks;
        $add_data['createtime'] = time();
        Db::name("szledger")->insertGetId($add_data);
        $this->success("账本添加成功");
    }
    public function getSzledger(){
        $data = Db::name("szledger")->where(['user_id'=>$this->auth->id])->select();
        $this->success("账本列表",$data);
    }

    public function deleteSzledger(){
        $id = $this->request->post('id');
        $data = Db::name("szledger")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        Db::name("szledger")->where(['id'=>$id])->delete();
        $this->success("账本删除");
    }
    public function saveSzledger(){
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        $remarks = $this->request->post('remarks','');
        if(!$name){
            $this->error("缺少必传参数");
        }
        $data = Db::name("szledger")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['name'] = $name;
        $add_data['remarks'] = $remarks;
        $add_data['updatetime'] = time();
        Db::name("szledger")->where(['id'=>$id])->update($add_data);
        $this->success("账本更新成功");
    }
    public function getSzledgerInfo(){
        $id = $this->request->post('id');
        $data = Db::name("szledger")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        $this->success("账本信息",$data);
    }
    public function addSzaccount(){
        $type = $this->request->post('type');
        $h_name = $this->request->post('h_name');
        $balance = $this->request->post('balance');
        $remarks = $this->request->post('remarks');
        $id_remarks = $this->request->post('id_remarks');
        $image = $this->request->post('image');
        $bank = $this->request->post('bank');
        $bank_account = $this->request->post('bank_account');
        $z_data = $this->request->post('z_data');
        $h_data = $this->request->post('h_data');
        $platform = $this->request->post('platform');


        $add_data['user_id'] = $this->auth->id;
        $add_data['type'] = $type;
        $add_data['h_name'] = $h_name;
        $add_data['balance'] = $balance;
        $add_data['remarks'] = $remarks;
        $add_data['id_remarks'] = $id_remarks;
        $add_data['image'] = $image;
        $add_data['bank'] = $bank;
        $add_data['bank_account'] = $bank_account;
        $add_data['z_data'] = $z_data;
        $add_data['h_data'] = $h_data;
        $add_data['platform'] = $platform;
        $add_data['createtime'] = time();
        Db::name("szaccount")->insertGetId($add_data);
        $this->success("账户添加成功");
    }
    public function getSzaccount(){
        $data = Db::name("szaccount")->where(['user_id'=>$this->auth->id])->select();
        $this->success("账本列表",$data);
    }
    public function getSzaccountInfo(){
        $id = $this->request->post('id');
        $data = Db::name("szaccount")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        $this->success("账本列表",$data);
    }
    public function deleteSzaccount(){
        $id = $this->request->post('id');
        $data = Db::name("szaccount")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        Db::name("szaccount")->where(['id'=>$id])->delete();
        $this->success("账本删除");
    }
    public function saveSzaccount(){
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        $h_name = $this->request->post('h_name');
        $balance = $this->request->post('balance');
        $remarks = $this->request->post('remarks');
        $id_remarks = $this->request->post('id_remarks');
        $image = $this->request->post('image');
        $bank = $this->request->post('bank');
        $bank_account = $this->request->post('bank_account');
        $z_data = $this->request->post('z_data');
        $h_data = $this->request->post('h_data');
        $platform = $this->request->post('platform');


        $data = Db::name("szaccount")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['type'] = $type;
        $add_data['h_name'] = $h_name;
        $add_data['balance'] = $balance;
        $add_data['remarks'] = $remarks;
        $add_data['id_remarks'] = $id_remarks;
        $add_data['image'] = $image;
        $add_data['bank'] = $bank;
        $add_data['bank_account'] = $bank_account;
        $add_data['z_data'] = $z_data;
        $add_data['h_data'] = $h_data;
        $add_data['platform'] = $platform;
        $add_data['createtime'] = time();
        Db::name("szaccount")->where(['id'=>$id])->update($add_data);
        $this->success("账本更新成功");
    }
    public function addSzinfo(){
        $type = $this->request->post('type');
        $classify_id = $this->request->post('classify_id');
        $ledger_id = $this->request->post('ledger_id');
        $account_id = $this->request->post('account_id');
        $in_date = $this->request->post('in_date');
        $images = $this->request->post('images');
        $house_id = $this->request->post('house_id');
        $money = $this->request->post('money');
        $in_user = $this->request->post('in_user');
        $remarks = $this->request->post('remarks');
        if(!$money || !$type || !$classify_id || !$ledger_id || !$account_id){
            $this->error("缺少必传参数");
        }
        $classify_data = Db::name("szclassify")->where(['id'=>$classify_id])->find();
        $ledger_data = Db::name("szledger")->where(['id'=>$ledger_id])->find();
        $account_data = Db::name("szaccount")->where(['id'=>$account_id])->find();
        if(!$classify_data || !$ledger_data || !$account_data){
            $this->error("参数有误");
        }
        if($type == 1){
            $str_type = '支出';
        }elseif ($type == 2){
            $str_type = '收入';
        }elseif ($type == 3){//转账
            $str_type = '转账';
        }elseif ($type == 4){//借贷
            $str_type = '借贷';
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['type'] = $type;
        $add_data['money'] = $money;
        $add_data['in_user'] = $in_user;
        $add_data['classify_id'] = $classify_id;
        $add_data['ledger_id'] = $ledger_id;
        $add_data['account_id'] = $account_id;
        $add_data['in_date'] = $in_date;
        $add_data['images'] = $images;
        $add_data['house_id'] = $house_id;
        $add_data['remarks'] = $remarks;
        $add_data['str_type'] = $str_type;
        $add_data['createtime'] = time();
        Db::name("szinfo")->insertGetId($add_data);
        $this->success("收支添加成功");
    }
    public function getSzinfo(){
        $where = [];
        $remarks = $this->request->post('remarks');
        $type = $this->request->post('type');
        $classify_id = $this->request->post('classify_id');
        $str_in_date = $this->request->post('str_in_date');
        $end_in_date = $this->request->post('end_in_date');
        $house_id = $this->request->post('house_id');
        $in_date_order = $this->request->post('in_date_order');
        $status = $this->request->post('status',-1);
        if(!$house_id){
            $this->error("缺少必传参数");
        }
        $where['house_id'] =  $house_id;
        if($remarks){
            $where['remarks'] =  ['like',"%".$remarks."%"];
        }
        if($type){
            $where['type'] =  $type;
        }
        if($str_in_date){
            $where['in_date'] =  ['>=',$str_in_date];
        }
        if($end_in_date){
            $where['in_date'] =  ['<=',$end_in_date];
        }
        if($classify_id){
            $where['classify_id'] =  $classify_id;
        }
        if($status >= 0){
            $where['status'] =  $status;
        }
        $order = "id dese";
        if($in_date_order){
            $order .= " in_date ".$in_date_order;
        }
        //
        $data = Db::name("szinfo")->where(['user_id'=>$this->auth->id])->where($where)->order($order)->paginate(20)->each(function ($item){
            if($item['status'] == 1){
                $item['status_str'] = "已审核";
            }else{
                $item['status_str'] = "待审核";
            }
            if($item['type'] == 1 || $item['type'] == 3){
                $item['money'] = "-".$item['money'];
            }
            $acc_data = Db::name("szaccount")->where(['id'=>$item['account_id']])->find();
            //var_dump($acc_data);
            if($acc_data){
                if($acc_data['type'] == 1){
                    $item['arrount_str'] =  $acc_data['h_name'];
                }elseif($acc_data['type'] == 2){
                    $item['arrount_str'] =  $acc_data['h_name']."|".$acc_data['bank']."|".substr($acc_data['bank_account'], -4);
                }else{
                    $item['arrount_str'] =  $acc_data['h_name'];
                }
            }else{
                $item['arrount_str'] = '';
            }

            $item['createtime'] = date('Y-m-d',$item['createtime']);
            return $item;
        });
        //echo Db::name("szinfo")->getLastSql();
        $zc_money = Db::name("szinfo")->where(['user_id'=>$this->auth->id,'type'=>1,'house_id'=>$house_id])->sum("money");
        $sr_money = Db::name("szinfo")->where(['user_id'=>$this->auth->id,'type'=>2,'house_id'=>$house_id])->sum("money");

        $rd_data['zc_money'] = $zc_money;
        $rd_data['sr_money'] = $sr_money;
        $rd_data['data'] = $data;
        $this->success("收支列表",$rd_data);
    }
    public function deleteSzinfo(){
        $ids = $this->request->post('ids');
       /* $data = Db::name("szinfo")->where(['user_id'=>$this->auth->id,'id'=>['in'=>$ids]])->find();
        if(!$data){
            $this->error("数据有误");
        }*/
        Db::name("szinfo")->where(['id'=>$ids])->delete();
        $this->success("收支删除");
    }
    public function getSzinfos(){
        $id = $this->request->post('id');
        $data = Db::name("szinfo")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $this->success("收支数据",$data);
    }
    public function saveSzinfo(){
        $id = $this->request->post('id');
        $type = $this->request->post('type');
        $classify_id = $this->request->post('classify_id');
        $ledger_id = $this->request->post('ledger_id');
        $account_id = $this->request->post('account_id');
        $in_date = $this->request->post('in_date');
        $images = $this->request->post('images');
        $house_id = $this->request->post('house_id');
        $money = $this->request->post('money');
        $in_user = $this->request->post('in_user');
        $remarks = $this->request->post('remarks');
        if(!$money || !$type || !$classify_id || !$ledger_id || !$account_id){
            $this->error("缺少必传参数");
        }
        $data = Db::name("szinfo")->where(['user_id'=>$this->auth->id,'id'=>$id])->find();
        if(!$data){
            $this->error("数据有误");
        }
        $add_data['user_id'] = $this->auth->id;
        $add_data['type'] = $type;
        $add_data['in_user'] = $in_user;
        $add_data['money'] = $money;
        $add_data['classify_id'] = $classify_id;
        $add_data['ledger_id'] = $ledger_id;
        $add_data['account_id'] = $account_id;
        $add_data['in_date'] = $in_date;
        $add_data['images'] = $images;
        $add_data['house_id'] = $house_id;
        $add_data['remarks'] = $remarks;
        $add_data['createtime'] = time();
        Db::name("szinfo")->where(['id'=>$id])->update($add_data);
        $this->success("收支更新成功");
    }
    public function upSzinfoStatus(){
        $ids = $this->request->post('ids');
        Db::name("szinfo")->where(['id'=>['in',$ids]])->update(['status'=>1]);
        $this->success("更改成功");
    }

}
